<?php
/**
 * Created by PhpStorm.
 * User: G
 * Date: 2021/3/27
 * Time: 下午3:25
 */

namespace app\api\command;

use app\admin\model\profit\Config;
use app\admin\model\profit\ProfitDetail;
use app\common\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\admin\model\profit\Agentapply as AgentApplyModel;
use think\Exception;

/*
 * 代理商申请 分润 定时任务
 */

class AgentApply extends Command
{

    /**
     * 名称描述配置
     * @author G
     * @date 2021-03-27 下午4:08
     */
    protected function configure()
    {
        $this->setName('agent_apply')->setDescription('Agent Apply Command');
    }

    /**
     * 分润处理
     * @param Input $input
     * @param Output $output
     * @return int|null|void
     * @author G
     * @date 2021-03-27 下午5:25
     */
    protected function execute(Input $input, Output $output)
    {
        // 业务处理
        $un_share_data = AgentApplyModel::where(['is_share' => 0, 'status' => 1])->select();
        if (!$un_share_data) {
            echo '暂无数据';
            return;
        }

        // 获取分润配置 3 : 卖区代，无推荐人
        $profit_config_3 = Config::getConfigById(3);

        // 获取分润配置 4 : 卖区代，365推荐
        $profit_config_4 = Config::getConfigById(4);

        // 获取分润配置 5 : 卖区代，区代/市代推荐
        $profit_config_5 = Config::getConfigById(5);

        // 获取分润配置 6 : 卖市代，365/区代推荐
        $profit_config_6 = Config::getConfigById(6);

        // 获取分润配置 7 : 卖市代，市代推荐
        $profit_config_7 = Config::getConfigById(7);

        foreach ($un_share_data as $k => $v) {
            // 更新 用户代理身份
            $update_group_res = User::where(['id' => $v['uid']])->update(['group_id' => $v['type'], 'updatetime' => time()]);
            if (!$update_group_res) {
                throw new Exception('更新用户代理身份信息失败');
            }

            // 查询申请人信息
            $apply_user_info = User::where('id', $v['uid'])->find();
            // 查询推荐人信息
            $invite_user_info = User::where('id', $v['p_uid'])->find();

            $temp_data = [
                'uid' => $apply_user_info['id'],
                'referrer_uid' => $v['p_uid'],
                're_referrer_uid' => $invite_user_info['referrer_uid'],
                'p_uid' => $apply_user_info['p_uid'],
                'c_uid' => $apply_user_info['c_uid'],
                'referrer_price' => 0,
                're_referrer_price' => 0,
                'p_price' => 0,
                'c_price' => 0,
                't_price' => 0,
                'print' => 0,
                'creat_time' => time(),
                'update_time' => time()
            ];

            if (!$invite_user_info || $invite_user_info['group_id'] == 1) {
                if ($v['type'] == 4 || (!$apply_user_info['p_uid'] && !$apply_user_info['c_uid'])) {
                    continue;
                } else {
                    if ($v['type'] == 3) {
                        // 方案 3
//                        $temp_data['c_price'] = 10000;
                        $temp_data['c_price'] = $profit_config_3['c_price'];
                        $temp_data['print'] = 3;
//                        $temp_data['t_price'] += 10000;
                        $temp_data['t_price'] += $profit_config_3['c_price'];
                    }
                }
            } else {
                if ($v['type'] == 3) {
                    // fixme 申请区代 需要查询是否有市代
                    $city_agent_user = User::where(['group_id' => 4, 'county_id' => $v['cc_id']])->find();
                    if ($city_agent_user) {
                        User::where(['id' => $v['uid']])->update(['c_uid' => $city_agent_user['id'], 'updatetime' => time()]);
                        // 重写市级代理
                        $temp_data['c_uid'] = $city_agent_user['id'];
                    }

                    if ($invite_user_info['group_id'] == 2) {
                        // 方案 4
//                        $temp_data['referrer_price'] = 5000;
                        $temp_data['referrer_price'] = $profit_config_4['referrer_price'];
                        $temp_data['re_referrer_price'] = $invite_user_info['referrer_uid'] ? $temp_data['referrer_price'] : 0;
//                        $temp_data['c_price'] = 3000;
                        $temp_data['c_price'] = $profit_config_4['c_price'];
                        $temp_data['print'] = 4;
//                        $temp_data['t_price'] += 8000;
                        $temp_data['t_price'] += ($temp_data['referrer_price'] + $temp_data['c_price']);
                    } else {
                        // 方案 5
//                        $temp_data['referrer_price'] = 10000;
                        $temp_data['referrer_price'] = $profit_config_5['referrer_price'];
                        $temp_data['re_referrer_price'] = $invite_user_info['referrer_uid'] ? $temp_data['referrer_price'] : 0;;
//                        $temp_data['c_price'] = 3000;
                        $temp_data['c_price'] = $profit_config_5['c_price'];;
                        $temp_data['print'] = 5;
//                        $temp_data['t_price'] += 13000;
                        $temp_data['t_price'] += ($temp_data['referrer_price'] + $temp_data['c_price']);
                    }
                } else if ($v['type'] == 4) {
                    // fixme 申请市代
                    if ($invite_user_info['group_id'] == 4) {
                        // 方案 7
//                        $temp_data['referrer_price'] = 100000;
                        $temp_data['referrer_price'] = $profit_config_7['referrer_price'];
                        $temp_data['re_referrer_price'] = $invite_user_info['referrer_uid'] ? $temp_data['referrer_price'] : 0;;
                        $temp_data['print'] = 7;
//                        $temp_data['t_price'] += 100000;
                        $temp_data['t_price'] += $temp_data['referrer_price'];
                    } else {
                        // 方案 6
//                        $temp_data['referrer_price'] = 50000;
                        $temp_data['referrer_price'] = $profit_config_6['referrer_price'];
                        $temp_data['re_referrer_price'] = $invite_user_info['referrer_uid'] ? $temp_data['referrer_price'] : 0;;
                        $temp_data['print'] = 6;
//                        $temp_data['t_price'] += 50000;
                        $temp_data['t_price'] += $temp_data['referrer_price'];
                    }
                }
            }

            $insert_res = ProfitDetail::insert($temp_data);
            if (!$insert_res) {
                throw new Exception('保存分润信息失败');
            }


            // 更新 用户表邀请人信息
            if (!$apply_user_info['referrer_uid']) {
                $update_referrer = User::where(['id' => $apply_user_info['id']])->update([
                    'province_id' => $v['p_id'],
                    'province_name' => $v['p_name'],
                    'city_id' => $v['c_id'],
                    'city_name' => $v['c_name'],
                    'county_id' => $v['cc_id'],
                    'county_name' => $v['cc_name'],
                    'referrer_uid' => $invite_user_info['id'],
                    'updatetime' => time()
                ]);
                if (!$update_referrer) {
                    throw new Exception('更新邀请人信息失败');
                }
            }

            // 更新区域代理信息
            if ($v['type'] == 3) {
                User::where(['county_id' => $v['cc_id']])
                    ->where('group_id', '<', 3)
                    ->where('group_id', '>', 1)
                    ->update([
                    'p_uid' => $apply_user_info['id'],
                    'updatetime' => time(),
                ]);
            } else if ($v['type'] == 4) {
                User::where(['city_id' => $v['c_id']])
                    ->where('group_id', '<', 4)
                    ->where('group_id', '>', 1)
                    ->update([
                    'c_uid' => $apply_user_info['id'],
                    'updatetime' => time(),
                ]);
            }

            // 更新分润状态：已分润
            $update_agent_res = AgentApplyModel::where(['id' => $v['id']])->update([
                'is_share' => 1,
                'updatetime' => time(),
            ]);

            if(!$update_agent_res) {
                throw new Exception('更新分润状态失败');
            }

            echo '成功: ' . $v['mobile'] . PHP_EOL;

        }
    }
}